<template>
  <div>
    <ConditionCard body-style="padding: 24px 24px 6px;" @search="search" @reset="reset">
      <el-form :model="condition" label-width="100px" ref="conditionForm">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item :label="$t('label.grade') + ':'" prop="grade">
              <el-date-picker
                v-model="condition.grade"
                value-format="yyyy"
                align="right"
                type="year"
                @change="selectChange"
                :placeholder="$t('common.pla.pleaseSelect')"
                clearable
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('label.college') + ':'" prop="college">
              <el-select v-model="condition.college" @change="initProfessionalOption" style="width: 100%" filterable clearable>
                <el-option v-for="item in options.college" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('label.major') + ':'" prop="professional">
              <el-select v-model="condition.professional" @change="professionChange" style="width: 100%" filterable
                clearable>
                <el-option v-for="item in options.professional" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item :label="$t('auditStandard.proDirection') + ':'" prop="direction">
              <el-select v-model="condition.direction" style="width: 100%" filterable clearable>
                <el-option v-for="item in options.direction" :key="item.key" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ConditionCard>
    <el-card shadow="never" body-style="padding: 0 24px 24px;">
      <div v-if="professionalTableData[0] && professionalTableData[0].data.length" class="professionalTable">
        <div class="clearfix" style="margin-bottom:16px">
          <div class="edu-page-title">{{$t("auditStandard.creditStandard")}}</div>
        </div>
        <edu-table :data="professionalTableData" :order="false" :pagination="false" border :selection="false"
          :merge='true' :stripe="false" :headerCellStyle="headerCellStyle" style="width: 100%;">
          <edu-table-column width="150" align="center" :label="$t('label.courseCategory')">
            <template slot-scope="scope">
              <div>
                {{scope.row.courseCategory}}
              </div>
            </template>
          </edu-table-column>
          <edu-table-column min-width="150" align="center" :label="item.labName"
            v-for="(item, key)  in professionalTableData[0].data" :key='key'>
            <template slot-scope="scope">
              <div v-if="scope.row.isEdit">
                <div v-if="scope.row.data[key]">
                  <el-input v-model="scope.row.data[key].credit" type="number" min="0"></el-input>
                </div>
              </div>
              <div v-else>
                <div v-if="scope.row.data[key]" style="margin: 0 auto;">{{scope.row.data[key].credit}}</div>
              </div>
            </template>
          </edu-table-column>
        </edu-table>
        <div class="float-right" style="margin-top: 16px;">
          <el-button @click="cancel">{{$t("message.cancel")}}</el-button>
          <el-button @click="confirm" type="primary">{{$t("message.confirm")}}</el-button>
        </div>
      </div>
    </el-card>
  </div>

</template>
<script>
  import {
    queryDic
  } from "common/src/api/dictionary";
import {HIDE_FACULTYCODE} from '../components/gradMangeUtis'
  import UTILS from "common/src/utils/utils";
  import api from 'common/src/api/graduationManagement/graduationManage';
  import {queryFacultyListByGrade} from 'common/src/api/graduationManagement/graduationManage';
  export default {
    data() {
      return {
        condition: {
          grade: '',
          college: '',
          professional: '',
          direction: ''
        },
        options: {
          college: [],
          professional: [],
          direction: []
        },
        professionalTableData: [],
        cacheData: [],
        isOverseas: '0'
      }
    },
    created() {
      //this.initCollageOption();
    },
    methods: {
      initCollageOption() {
        // const data = {
        //   lang: this.$store.getters.language || "cn",
        //   type: "allChild",
        //   keys: ["X_YX"]
        // };
        this.condition.college = '';
        this.options.college = [];
        const data = {
            grade: this.condition.grade
        }
        if (!data.grade) {
            return;
        }
        queryFacultyListByGrade(data).then(res => {
          if (res.code === 200) {
                this.options.college = (res.data || []).map(item => {
                    return {
                        label: item.facultyNameI18n,
                        value: item.facultyCode,
                        key: item.facultyCode
                    }
                })
            // UTILS.fillSelect({
            //     college: "X_YX"
            //   },
            //   res.data,
            //   this.options
            // );
            // this.options.college = this.options.college.filter(item => {
            //     return (HIDE_FACULTYCODE || []).indexOf(item.value) === -1;
            // })
          }
        });
      },
      initProfessionalOption() {
        this.options.professional = [];
        this.condition.professional = '';
        this.options.direction = [];
        this.condition.direction = '';
        if (!this.condition.college || !this.condition.grade) {
          return;
        }
        let param = {
          faculty: this.condition.college,
          grade: this.condition.grade,
          pageNum_: 1,
          pageSize_: 100,
          projId: "1"
        }
        api.getProfessionList(param).then(res => {
          if (res && res.code === 200) {
            let listData = res.data && res.data.list || [];
            let options = [];
            listData.forEach(item => {
              if (item.professionCode) {
                options.push({
                  key: item.professionCode,
                  value: item.professionCode,
                  label: item.professionName
                })
              }
            })
            this.options.professional = options;
          }
        })
      },
      initDirection() {
        this.options.direction = [];
        this.condition.direction = '';
        if (this.condition.grade && this.condition.professional) {
          let params = {
            pageNum_: 1,
            pageSize_: 20,
            grade: this.condition.grade,
            professionCode: this.condition.professional
          };
          api.findDirMaintenList(params).then(res => {
            if (res && res.code === 200) {
              let listData = res.data && res.data.list || [];
              let options = [];
              listData.forEach(item => {
                if (item.code) {
                  options.push({
                    key: item.code,
                    value: item.code,
                    label: item.name
                  })
                }
              })
              this.options.direction = options;
            }
          })
        }

      },
      selectChange() {
        this.initCollageOption();
        this.initProfessionalOption();
      },
      professionChange() {
        this.initDirection();
      },
      reset() {
        this.$refs.conditionForm.resetFields();
        this.options.college = [];
        this.options.professional = [];
        this.options.direction = [];
        this.professionalTableData = [];
        this.cacheData = [];
      },
      search() {
        this.getStandard();
      },
      getStandard() {
        if (this.condition.grade) {
          let params = {
            ...this.condition
          };
          api.geStandardLabel(params).then(res => {
            this.professionalTableData = [];
            this.cacheData = [];
            if (res && res.code === 200) {
              let {
                labelStandard
              } = res.data || {};
              this.handleLabelStandard(labelStandard);
            }
          }).catch(() =>{
            this.professionalTableData = [];
            this.cacheData = [];
          })
        }else {
          this.$message({
            message: this.$t('auditStandard.selectGradeTip'),
            type: 'warning'
          });
          this.professionalTableData = [];
          this.cacheData = [];
        }
      },
      handleLabelStandard(data) {
        if (!data || !data.length) {
          return;
        }
        this.labelStandardData = data;
        this.cacheData = _.cloneDeep(data);
        let labIdMap = {};
        data.forEach(item => {
          item.credit = item.credit || 0;
          if (item.orderNum !== 999) {
            if (!item.parentLabID) {
              let labID = item.labID + '_';
              if (!labIdMap[labID]) {
                labIdMap[labID] = [];
              }
              labIdMap[labID].push(item);
            } else {
              let parentLabID = item.parentLabID + '_';
              if (!labIdMap[parentLabID]) {
                labIdMap[parentLabID] = [];
              }
              labIdMap[parentLabID].push(item);
            }
          }
        });
        let newList = [{
            courseCategory: this.$t('auditStandard.creditRequirements'),
            data: [],
            isEdit: true
          },
          {
            courseCategory: this.$t('auditStandard.creditTotal'),
            data: []
          }
        ];
        for (let key in labIdMap) {
          labIdMap[key].sort((item1, item2) => {
            return item2.orderNum - item1.orderNum;
          })
          let len = newList[1].data.length;
          if (labIdMap[key] && labIdMap[key].length > 1) {
            let num = 0;
            let parentCredit = 0;
            let parentItem = null;
            labIdMap[key].forEach(v => {
              if (v.parentLabID) {
                newList[0].data.push(v);
                if (v.credit) {
                  parentCredit += Number(v.credit);
                }
                num++;
              } else {
                parentItem = v;
                newList[1].data.push(v);
              }
            })
            parentItem && (parentItem.credit = parentCredit);
            if (!newList[1].columnList) {
              newList[1].columnList = [];
            }
            num > 1 && (newList[1].columnList.push({
              index: len + 1,
              rowspan: 1,
              colspan: num
            }));
          } else {
            if (labIdMap[key].length === 1) {
              newList[0].data.push(labIdMap[key][0]);
              newList[1].data.push(labIdMap[key][0]);
            }
          }
        }
        this.professionalTableData = newList;
      },
      headerCellStyle() {
        return "background: #f4f7fa";
      },
      confirm() {
        let params = [];
        if (this.labelStandardData) {
          this.labelStandardData.forEach(item => {
            let paramItem = {
              label: item.labID,
              labelName: item.labName,
              parentLabel: item.parentLabID,
              parentLabelName: item.parentLabName,
              credits: Number(item.credit),
              isOverseas: this.isOverseas,
              ...this.condition
            }
            if (item.orderNum === 999) {
              paramItem.credits = this.calcuTotalCredit();
              paramItem.label = 999;
            }
            params.push(paramItem);
          });
          api.saveStandardLabel(params).then(res => {
            if (res && res.code === 200) {
              this.$message({
                message: this.$t('auditStandard.setProfessionalAuditStandardSuccessTip'),
                type: 'success'
              }); 
              this.getStandard();
            }
          })
        }
      },
      cancel() {
        this.handleLabelStandard(this.cacheData);
      },
      calcuTotalCredit() {
        let total = 0;
        let [{
          data
        }] = this.professionalTableData;
        if (data) {
          data.forEach(item => {
            total += Number(item.credit);
          })
        }
        return total;
      }
    },
    watch: {
      professionalTableData: {
        handler(newVal, oldval) {
          if (newVal.length) {
            let [firstLineData = {}, secondLineData = {}] = newVal;
            if (secondLineData.data && firstLineData.data) {
              secondLineData.data.forEach(item => {
                if (!item.parentLabID) {
                  let findData = firstLineData.data.filter(v => {
                    return v.parentLabID === item.labID;
                  })
                  if (findData.length) {
                    let total = 0;
                    findData.forEach(spec => {
                      total += Number(spec.credit);
                    })
                    item.credit = total;
                  }
                }
              })
            }
          }
        },
        deep: true
      }
    }
  }

</script>
<style scoped lang="scss">
  ::v-deep .cell.el-tooltip {
    margin: 0 auto;
  }

  .professionalTable ::v-deep .el-form-item {
    margin-bottom: 0px;
  }

</style>
